/*
 * This file is part of Smart Route for S60 3rd Edition terminals
 * 
 * Copyright (C) 2006  Harri Salminen

 * This program free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 *(at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
 
#include "ExportRoute.h"
#include "SmartRouteDocument.h"
#include "eikappui.h"

CExportRoute::CExportRoute(CSmartRoute& aRoute) :
	iRoute(aRoute)
	{
	}


CExportRoute::~CExportRoute()
	{
	delete iExportedRoute;
	}

CExportRoute* CExportRoute::NewLC(CSmartRoute& aRoute)
	{
	CExportRoute* self = new (ELeave)CExportRoute(aRoute);
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}

CExportRoute* CExportRoute::NewL(CSmartRoute& aRoute)
	{
	CExportRoute* self=CExportRoute::NewLC(aRoute);
	CleanupStack::Pop(); // self;
	return self;
	}

void CExportRoute::ConstructL()
	{
	iExportedRoute = CBufFlat::NewL(512);
	}
	
TPtr8 CExportRoute::ExportRouteL()	
	{
	TBuf<128> outBuf;
	
	CEikAppUi* eikapp = static_cast<CEikAppUi*>(CEikonEnv::Static()->AppUi());
	CSmartRouteDocument* doc = static_cast<CSmartRouteDocument*>(eikapp->Document());
	iExportedRoute->Reset();
	
	AddL(KXMLHeader);
	AddL(KKMLHeader);
	AddL(KPlacemark); 
	
	AddL(KName);
	AddL(iRoute.Name());
	AddL(KNameClose);
	
	AddL(KStyle);
	AddL(KLineStyle);
	AddL(KColor);
	AddL(doc->Color());
	AddL(KColorClose);
	AddL(KWidth);
	outBuf.Format(_L("%f"), doc->LineWidth());
	AddL(outBuf);
	AddL(KWidthClose);
	AddL(KLineStyleClose);
	AddL(KStyleClose);
	
	AddL(KLineString);
	AddL(KCoordinates);
	TRoutePoint point; 
	RRoutePointArray routePoints = iRoute.Points(); 

	for(TInt i=0; i < iRoute.Points().Count(); i++)
		{
		point = routePoints[i];
		outBuf.Format(_L("%f,%f\n"), point.iLongitude, point.iLatitude);
		AddL(outBuf); 
		}
	AddL(KCoordinatesClose); 
	AddL(KLineStringClose);
	
	AddL(KPlacemarkClose);
	AddL(KKMLClose);
	
	return iExportedRoute->Ptr(0); 
	}

void CExportRoute::AddL(const TDesC8& aData)
	{
	iExportedRoute->InsertL(iExportedRoute->Size(), aData);
	}
	
void CExportRoute::AddL(const TDesC16& aData)
	{
	HBufC8* tmp = HBufC8::NewLC(aData.Length());
	TPtr8 tmpPtr = tmp->Des();
	tmpPtr.Copy(aData);
	
	iExportedRoute->InsertL(iExportedRoute->Size(), *tmp);
	CleanupStack::PopAndDestroy(); //tmp
	}